package com.heneng.bluetoothdemo;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";

    private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";   //SPP服务UUID号
    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();    //获取本地蓝牙适配器，即蓝牙设备
    BluetoothDevice _device = null;   //蓝牙设备
    BluetoothSocket _socket = null;   //蓝牙通信socket
    private InputStream is;    //输入流，用来接收蓝牙数据
    private RadioButton mRbPrint;
    private BluetoothAdapter mBtAdapter;
    private Button mBtnConnectPrint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBluetooth();

        setContentView(R.layout.activity_main);
        mRbPrint = findViewById(R.id.rb_print);
        mBtnConnectPrint = findViewById(R.id.btn_connect_print);
        mBtnConnectPrint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectPrint();
            }
        });
        findViewById(R.id.btn_print).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                PrintEvent printEvent = new PrintEvent();
                printEvent.print_type = Constant.DRIVER_WAY_FRAGMENT;
                printEvent.location = "海南省海南省陵水黎族自治县滨河南路231号靠近陵水黎族自治县业余体育学校";
                printEvent.time = "2021-11-16 09:42:44";
                printEvent.heidu = "0.25 合格";
                printEvent.plate_num = "琼D15409";
                printEvent.vehicle_type = "小型普通客车";
                printEvent.owner = "陵水黎族自治县城市管理局";
                printEvent.use_character = "非营运";
                printEvent.address = "海南省陵水黎族自治县椰林镇新丰路4号";
                printEvent.model = "吉利全球鹰牌RX6453K02";
                printEvent.vin = "L106D2A56D1035582";
                printEvent.engine_num = "CCJD00025";
                printEvent.register_date = "20130313";
                printEvent.issue_date = "20100313";
                printEvent.driver_way = "机动车";
                printEvent.modify = "查看";
                printEvent.uuid = "1637026992734270472";

                PrintUtil2.printTest(printEvent.getPrint_type(), _socket, printEvent);
            }
        });
    }

    private void print(PrintEvent printEvent) {
        PrintUtil2.printTest(printEvent.getPrint_type(), _socket, printEvent);
    }


    private boolean initBluetooth() {
        //如果打开本地蓝牙设备不成功，提示信息，结束程序
        if (_bluetooth == null) {
            Toast.makeText(this, "无法打开手机蓝牙，请确认手机是否有蓝牙功能！", Toast.LENGTH_LONG).show();
            finish();
            return true;
        }

        // 得到本地蓝牙句柄
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        getApplicationContext().registerReceiver(mReceiver, intentFilter);
        return false;
    }

    // 查找到设备和搜索完成action监听器
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, action);
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_ON:
                        connectPrint();
                        break;
                }
            }
            // 查找到设备action
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 得到蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d("bluetooth", "蓝牙设备：" + device.getName());
                if (device != null && device.getName() != null) {
                    if (device.getName().equals("CS3_4517") || device.getName().contains("MPT-II") || device.getName().equals("58HB6")) {
                        connectPrinter(device.getAddress());
                    }

                }
                // 搜索完成action
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (_socket != null) {
                    return;
                }
                //                dialog.dismiss();
                dismissWaitingDialog();

                Toast.makeText(MainActivity.this, "找不到打印机，请检查设备是否开启！", Toast.LENGTH_LONG).show();

            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                Toast.makeText(MainActivity.this, "打印机已断开", Toast.LENGTH_LONG).show();
                closeSocket();
            }
        }
    };

    private void connectPrinter(String address) {
        _bluetooth.cancelDiscovery();
        // 得到蓝牙设备句柄
        _device = _bluetooth.getRemoteDevice(address);
        try {
            _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
            _socket.connect();
            Toast.makeText(this, "连接打印机成功！", Toast.LENGTH_SHORT).show();
            _bluetooth.cancelDiscovery();
            mBtnConnectPrint.setText("断开打印机");
            mRbPrint.setChecked(true);
            is = _socket.getInputStream();   //得到蓝牙数据输入流


        } catch (IOException e) {
            e.printStackTrace();
            try {
                Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                _socket.close();
                _socket = null;
            } catch (IOException ee) {
                ee.printStackTrace();
                Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
            }
        }
        dismissWaitingDialog();
        //        dialog.dismiss();
    }


    private void connectPrint() {
        if (mRbPrint.isChecked()) {
            disconnectBluetooth();
        } else {
            connectBluetooth();
        }
    }

    private void connectBluetooth() {
        int i = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);

        if (i != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            if (_bluetooth.isEnabled() == false) {  //如果蓝牙服务不可用则提示
                //                dialog.show();
                showWaitingDialog("正在连接，请稍等", false);
                _bluetooth.enable();
                return;
            } else {
                showWaitingDialog("正在连接，请稍等", false);
                //                if (!dialog.isShowing()) {
                //                    dialog.show();
                //                }
                doDiscovery();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    connectBluetooth();
                } else {
                    Toast.makeText(this, "你拒绝了权限授予", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    /**
     * 开始服务和设备查找
     */
    private void doDiscovery() {

        // 关闭再进行的服务查找
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        mBtAdapter.startDiscovery();
    }

    private void disconnectBluetooth() {
        //关闭连接socket
        if (_device != null) {
            Toast.makeText(MainActivity.this, " 断开打印机中...", Toast.LENGTH_SHORT).show();
        }
        closeSocket();
    }

    private void closeSocket() {
        try {
            if (is != null) {
                is.close();
            }
            if (_socket != null) {
                _socket.close();
            }
            _socket = null;
            _device = null;

            mRbPrint.setChecked(false);

            mBtnConnectPrint.setText("连接打印机");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
